import React, { FC,useEffect } from 'react'
import { Form,Input,Checkbox,Space,Button } from 'antd'
import { QuestionCheckboxDefaultProps, QuestionCheckboxPropsType } from './interface.ts'
import { OptionType } from './interface.ts'
import { MinusCircleOutlined,PlusOutlined } from '@ant-design/icons'
import {nanoid} from 'nanoid'
const PropComponent: FC<QuestionCheckboxPropsType> = (props:QuestionCheckboxPropsType)=>{
    const {title,isVertical,list = [],onChange,disabled} =  props

    const [form] = Form.useForm()

    useEffect(() => {
            form.setFieldsValue({ title, isVertical, list })
        }, [title, isVertical, list])
    
        const handleValuesChange = () => {
            if (onChange == null) return
            // 触发 onChange 函数
            const newValues = form.getFieldsValue() as QuestionCheckboxPropsType  // 就是 QuestionRadioPropsType格式不过对应的都有值
            console.log('newValues',newValues); 
            
            const { list = [] } = newValues
            list.forEach((opt:any) => {
                if(opt.value) return 
                opt.value = nanoid(5) // 5代表长度
            })
            onChange(newValues) // 同步过去 redux-store
        }

    return (
        <Form
            layout='vertical'
            form={form}
            initialValues={{title,isVertical,list}}
            disabled={disabled}
            onValuesChange={handleValuesChange}
        >
            <Form.Item label="标题" name="title" rules={[{ required: true,message:'请输入标题' }]}>
                <Input />
            </Form.Item>
            <Form.Item label="选项">
                <Form.List name="list">
                    {(fields:any, { add, remove }) => (
                        <>
                            {/* 遍历所有选项 可删除 */}
                            {fields.map(({ key, name, ...restField }, index:any) => (
                                <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                    {/* 当前项 是否选中 */}
                                    {/* valuePropName='checked' 旨在用checked  代替Checkbox的value属性 */}
                                    <Form.Item name={[name, 'checked']} valuePropName='checked'>
                                        <Checkbox />
                                    </Form.Item>
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'text']}
                                        rules={[
                                            { required: true, message: '请输入选项文字' },
                                            {
                                                validator: (_, text) => {
                                                    const { list = [] } = form.getFieldsValue()
                                                    let num = 0
                                                    list.forEach((opt: OptionType) => {
                                                        if (opt.text === text) num++ // 记录 text 相同的个数，预期只有 1 个（自己）
                                                    })
                                                    if (num === 1) return Promise.resolve()
                                                    return Promise.reject(new Error('和其他选项重复了'))
                                                },
                                            },
                                        ]}
                                    >
                                        <Input placeholder="请输入选项文字..." />
                                    </Form.Item>
                                    {index > 0 &&
                                        <MinusCircleOutlined onClick={() => remove(name)} />
                                    }
                                </Space>
                            ))}
                            {/* 添加选项 */}
                            <Form.Item>
                                <Button type="link" onClick={() => add({ text: '', value: '', checked:false })} block icon={<PlusOutlined />}>
                                    添加选项
                                </Button>
                            </Form.Item>
                        </>
                    )}
                </Form.List>
            </Form.Item>
            <Form.Item name="isVertical" valuePropName="checked">
                <Checkbox>竖向排列</Checkbox>
            </Form.Item>
        </Form>
    )
}

export default PropComponent